//
//  YHHoemAgentMakeShareMoneySubViewController.m
//  YHApp
//
//  Created by -- on 2021/11/16.
//

#import "HAHoemAgentMakeShareMoneySubVC.h"

#import "HAShareMoneyModMo.h"
#import "HAChoiceShareMoneyModPopView.h"
#import "HAMeSettlementItemMo.h"
#import "HAHoemAgentMakeShareMoneyContentCell.h"

@interface HAHoemAgentMakeShareMoneySubVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
/***/
@property (nonatomic, strong) NSMutableArray *shareMoneyModArray;
/***/
@property (nonatomic, strong) NSMutableArray *modArray;

/***/
@property (nonatomic, strong) HAShareMoneyModMo *selModModel;

@end

@implementation HAHoemAgentMakeShareMoneySubVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor khaBGColor];

    [self setupUI];
//    [self loadData];
    [self loadModData:nil];

}

-(void)loadData {
    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodGET;
    request.requestUrl = @"profit/lists";
    [MBProgressHUD showLoading:self.view];
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            
            [MBProgressHUD hideHUDForView:self.view];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HAShareMoneyModMo mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.shareMoneyModArray removeAllObjects];
                    [self.shareMoneyModArray addObjectsFromArray:arr];
                    if (self.shareMoneyModArray.count > 0) {
                        [self.dataArray removeAllObjects];
                        [self.dataArray addObject:@"选择模板"];
                        [self.tableView reloadData];
                        
                        [self loadModData:nil];
                    }
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            [self.tableView reloadData];
        }
    }];
}

-(void)loadModData:(HAShareMoneyModMo *)model {
    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodGET;
    request.requestUrl = @"profit/canalProfitFields";
    request.parms = @{
        @"agent_id":self.agent_id?:@"",
        @"profit_id":model.ID?:@"",
        @"code":self.canalItemModel.value?:@"",
    };
    
    [MBProgressHUD showLoading:self.view];
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            
            [MBProgressHUD hideHUDForView:self.view];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                NSArray *arr = [HAMeSettlementItemMo mj_objectArrayWithKeyValuesArray:dataModel.data];
                [self.modArray removeAllObjects];
                [self.modArray addObjectsFromArray:arr];
                if (self.modArray.count > 0) {
                    [self.dataArray removeAllObjects];
//                    [self.dataArray addObject:@"选择模板"];
                    [self.dataArray addObject:@"内容"];
                    [self.dataArray addObject:@"提交"];
                    [self.tableView reloadData];
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            [self.tableView reloadData];
        }
    }];
}

-(void)setupUI {
    
    UILabel *exLabel = [UILabel ha_NLabelWithFont:13 textColor:@"#858b9c" text:@"商户费率-代理结算成本<0（负数），计算分润为0。" alignment:0];
    [self.view addSubview:exLabel];
    [exLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
        make.top.mas_equalTo(0);
        make.height.mas_offset(43);
    }];

    UIView *lineView = [UIView ha_createView];
    lineView.backgroundColor = [UIColor kLineColor];
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(43);
        make.height.mas_offset(1);
    }];


    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(44);
        make.bottom.mas_equalTo(0);
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataArray[indexPath.row];
    if ([title isEqualToString:@"选择模板"]) {
        return 56;
    }
    if ([title isEqualToString:@"内容"]) {
        CGFloat h = 0;
        h += (20+54+28) * self.modArray.count;
        return h;
    }
    if ([title isEqualToString:@"提交"]) {
        return 54+60;
    }
    return 0;
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataArray[indexPath.row];
    if ([title isEqualToString:@"内容"]) {
        HAHoemAgentMakeShareMoneyContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHHoemAgentMakeShareMoneyContentCellID"];
        if (!cell) {
            cell = [[HAHoemAgentMakeShareMoneyContentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YHHoemAgentMakeShareMoneyContentCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.modArray = self.modArray;
        return cell;
    }else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHMeSettlementMakeMitCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YHMeSettlementMakeMitCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([title isEqualToString:@"选择模板"]) {
            [self setCellMod:cell.contentView];
        }
        if ([title isEqualToString:@"提交"]) {
            [self setCellMit:cell.contentView];
        }
        return cell;
    }
    return [UITableViewCell new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WS(weakSelf)
    NSString *title = self.dataArray[indexPath.row];
    if ([title isEqualToString:@"选择模板"]) {
        HAChoiceShareMoneyModPopView *menu = [[HAChoiceShareMoneyModPopView alloc]initWithArray:self.shareMoneyModArray];
        [menu show];
        menu.YHChoiceShareMoneyModMenuSureBlock = ^(HAShareMoneyModMo * _Nonnull model) {
            weakSelf.selModModel = model;
            [weakSelf loadModData:model];
        };
    }

}

-(void)setCellMod:(UIView *)contentView {
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    contentView.backgroundColor = [UIColor khaBGColor];

    UIView *mainV = [UIView ha_createView];
    mainV.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:mainV];
    [mainV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(2);
        make.bottom.mas_equalTo(0);
    }];
    
    UILabel *titlabel = [UILabel ha_NLabelWithFont:17 textColor:@"#000000" text:@"利润模板" alignment:0];
    [mainV addSubview:titlabel];
    [titlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(20);
        make.width.mas_offset(100);
    }];
    
    UIImageView *RImgV = [UIImageView ha_createImageView];
    RImgV.image = [UIImage imageNamed:@"ic_cell_more"];
    [mainV addSubview:RImgV];
    [RImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(5);
        make.height.mas_offset(10);
        make.centerY.mas_equalTo(0);
        make.right.mas_equalTo(-20);
    }];

    
    UILabel *conLabel = [UILabel ha_NLabelWithFont:15 textColor:@"#858b9c" text:@"请选择模板" alignment:2];
    [contentView addSubview:conLabel];
    [conLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(titlabel.mas_right).offset(15);
        make.right.mas_equalTo(-10-20-10);
    }];
    
    if (self.selModModel) {
        conLabel.text = self.selModModel.name;
        conLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    }else {
        conLabel.text = @"请选择";
        conLabel.textColor = [UIColor colorWithHexString:@"#858b9c"];
    }
}

-(void)setCellMit:(UIView *)contentView {
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    contentView.backgroundColor = [UIColor khaBGColor];
    UIButton *mitButton = [[UIButton alloc]init];
    [mitButton setTitle:@"提交" forState:UIControlStateNormal];
    [mitButton setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
    mitButton.titleLabel.font = [UIFont systemFontOfSize:20];
    mitButton.backgroundColor = [UIColor colorWithHexString:@"#19191A"];
    [mitButton addTarget:self action:@selector(mitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:mitButton];
    [mitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.centerY.mas_equalTo(0);
        make.height.mas_offset(54);
    }];
}


-(void)mitButtonClick{

    [self.view endEditing:YES];
    
    NSMutableArray *mitAateArr = [NSMutableArray array];
    for (int i = 0; i < self.modArray.count; i ++) {
        HAMeSettlementItemMo *rateMo = self.modArray[i];
        [mitAateArr addObject:@{
            @"value":rateMo.value?:@"",
            @"field":rateMo.field?:@"",
        }];
    }

    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodPOST;
    request.requestUrl = [NSString stringWithFormat:@"profit/profit"];
    request.parms = @{
        @"item":[mitAateArr mj_JSONString],
        @"agent_id":self.agent_id?:@"",
        @"profit_id":self.selModModel.ID?:@"",
        @"source_id":self.canalItemModel.value?:@"",
    };
    [MBProgressHUD showLoading:self.view];

    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                [MBProgressHUD showSuccess:@"提交成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [MBProgressHUD showError:dataModel.msg];
            }
        }
    }];

}


- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)shareMoneyModArray
{
    if (!_shareMoneyModArray) {
        _shareMoneyModArray = [NSMutableArray array];
    }
    return _shareMoneyModArray;
}

- (NSMutableArray *)modArray
{
    if (!_modArray) {
        _modArray = [NSMutableArray array];
    }
    return _modArray;
}




@end
